/*
 * @Author: szx
 * @Date: 2022-03-02 13:52:33
 * @LastEditTime: 2022-03-02 14:23:02
 * @Description:
 * @FilePath: \leetcode\1-99\76\76.js
 */
/**
 * @param {string} s
 * @param {string} t
 * @return {string}
 */
var minWindow = function (s, t) {
    const map = new Map();
    for (let i = 0; i < t.length; i++) map.set(t[i], (map.get(t[i]) || 0) + 1);
    let i = 0,
        j = 0;
    let window = {};
    let num = 0,
        res = '',
        length = Number.MAX_SAFE_INTEGER;
    while (j < s.length) {
        let ch = s[j];
        if (map.has(ch)) {
            window[ch] = (window[ch] || 0) + 1;
            if (map.get(ch) == window[ch]) num++;
        }
        while (num == map.size) {
            let c = s[i];
            if (map.has(c)) {
                if (length > j - i + 1) {
                    res = s.substring(i, j + 1);
                    length = j - i + 1;
                }
                window[c]--;
                if (window[c] < map.get(c)) num--;
            }
            i++;
        }
        j++;
    }
    return res;
};
console.log(minWindow('ADOBECODEBANC', 'ABC'));
console.log(minWindow('a', 'a'));
console.log(minWindow('a', 'aa'));
console.log(minWindow('aab', 'aab'));
